﻿using System.Collections.Generic;
using System.Xml;
using System.Linq;
using NJabber.Client;

namespace NJabber.Stream.Elements
{
    public class RosterItemElement : XmppStreamElement
    {
        private ICollection<string> groups;

        public RosterItemElement(string itemName) : this(itemName, null)
        {}

        public RosterItemElement(string itemName, JID jid) : this(itemName, jid, "")
        {}

        public RosterItemElement(string itemName, JID jid, IEnumerable<string> groups) : this(itemName, jid)
        {
            foreach (string @group in groups) this.groups.Add(group);
        }

        public RosterItemElement(string itemName, JID jid, string subscription) : base("item")
        {
            groups = new List<string>();
            ItemName = itemName;
            Jid = jid;
            Subscription = subscription;
        }

        public string ItemName
        {
            get { return (string) GetAttributeValue("name"); }
            set { SetAttributeValue("name", value); }
        }

        public JID Jid
        {
            get { return (JID) GetAttributeValue("jid"); }
            set { SetAttributeValue("jid", value); }
        }

        public ICollection<string> Groups
        {
            get { return groups; }
        }

        public string Subscription
        {
            get { return (string) GetAttributeValue("subscription"); }
            set { SetAttributeValue("subscription", value); }
        }

        public void AddGroups(params string[] groupNames)
        {
            foreach (string groupName in groupNames) Groups.Add(groupName);
        }

        protected override void WritePayload(XmlWriter writer)
        {
            foreach (string groupName in Groups)
            {
                writer.WriteElementString("group", groupName);
            }
        }

        public override bool Equals(object obj)
        {
            RosterItemElement rosterItem = obj as RosterItemElement;
            if (rosterItem == null) return false;

            return Equals(rosterItem);
        }

        public bool Equals(RosterItemElement item)
        {
            return base.Equals(item) && Groups.SequenceEqual(item.Groups);
        }

        public static implicit operator RosterItem(RosterItemElement itemElement)
        {
            return new RosterItem(itemElement.ItemName, itemElement.Jid, itemElement.Groups);
        }
    }
}
